<template>
  <div>
    <el-form :inline="true" class="demo-form-inline" :model="cForm">
      <el-form-item label="一级分类">
        <el-select placeholder="请选择" v-model="cForm.category1Id" @change="getCategory2List" :disabled="show">
          <el-option :label="c1.name" :value="c1.id" v-for="(c1, index) in category1List" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select placeholder="请选择" v-model="cForm.category2Id" @change="getCategory3List" :disabled="show">
          <el-option :label="c2.name" :value="c2.id" v-for="(c2, index) in category2List" :key="index"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select placeholder="请选择" v-model="cForm.category3Id" @change="getCategory3Id" :disabled="show">
          <el-option :label="c3.name" :value="c3.id" v-for="(c3, index) in category3List" :key="index"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'CategorySelect',
  data() {
    return {
      // 收集相应的一级,二级,三级分类的请求列表
      category1List: [],
      category2List: [],
      category3List: [],
      // 收集相应的一级,二级,三级分类的id
      cForm: {
        category1Id: '',
        category2Id: '',
        category3Id: ''
      }
    }
  },
  mounted() {
    // 获取一级分类列表
    this.getCategory1List()
  },
  methods: {
    // 获取一级分类列表
    async getCategory1List() {
      let result = await this.$API.attr.reqCategory1List()
      if (result.code == 200) {
        this.category1List = result.data
      }
    },
    // 获取二级分类列表(一级分类改变时)
    async getCategory2List() {
      // 清除数据
      this.category2List = []
      this.category3List = []
      this.cForm.category2Id = ''
      this.cForm.category3Id = ''
      // 发起请求
      let { category1Id } = this.cForm
      let result = await this.$API.attr.reqCategory2List(category1Id)
      if (result.code == 200) {
        this.category2List = result.data
      }
      // 传递id值
      this.$emit('getCategoryId', { categoryId: category1Id, level: 1 })
    },
    // 获取三级分类列表(二级分类改变时)
    async getCategory3List() {
      // 清除数据
      this.category3List = []
      this.cForm.category3Id = ''
      // 发起请求
      let { category2Id } = this.cForm
      let result = await this.$API.attr.reqCategory3List(category2Id)
      if (result.code == 200) {
        this.category3List = result.data
      }
      // 传递id值
      this.$emit('getCategoryId', { categoryId: category2Id, level: 2 })
    },
    // 三级分类改变时
    getCategory3Id() {
      let { category3Id } = this.cForm
      this.$emit('getCategoryId', { categoryId: category3Id, level: 3 })
    }
  },
  // 接收isShowTable参数
  props:['show']
}
</script>

<style></style>